package com.lg.common.network

import android.content.Context
import com.lg.common.activities.BaseActivity
import com.lg.common.activities.BaseActivity.Companion.mDataBaseHandler
import com.lg.common.activities.BaseActivity.Companion.mGson
import com.lg.common.models.BaseModel
import com.lg.common.utils.ApplicationConstants.ENABLE_OFFLINE_MODE
import com.lg.common.utils.Utils.Companion.disableUserInteraction
import com.lg.common.utils.Utils.Companion.enableUserInteraction

import io.reactivex.Observer
import io.reactivex.disposables.Disposable



open class ApiCustomCallback<R : BaseModel>(val context: Context, val isDisableInteraction: Boolean) : Observer<R> {

    override fun onSubscribe(disposable: Disposable) {
        try {
            (context as BaseActivity).mCompositeDisposable.add(disposable)
            if (isDisableInteraction)
                disableUserInteraction(context)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onNext(responseModel: R) {
        try {
            enableUserInteraction(context)
            if ((responseModel as BaseModel).success) {
                if (ENABLE_OFFLINE_MODE && (context as BaseActivity).mHashIdentifier.isNotEmpty())
                    mDataBaseHandler.addOrUpdateIntoOfflineTable(context.mHashIdentifier, responseModel.eTag, mGson.toJson(responseModel))
            } else {
//                ToastHelper.showToast(context, (t as BaseModel).message)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onError(e: Throwable) {
        enableUserInteraction(context)
        e.printStackTrace()
    }

    override fun onComplete() {
        enableUserInteraction(context)
    }
}